<?php

require_once dirname(__DIR__) . '/lib/utils.php';
require_once __DIR__ . '/SpiderModel.php';

/**
 * 定时任务
 * 大乐透开奖时间：每周一、三、六 21:25 开奖
 * 双色球开奖时间：每周二、四、日 21：15 开奖
 * 每天 21:30 执行一次 30 21 * * * php /www/wwwroot/lucklottery/dist/task.php
 * @version 1.0.0
 */
class TaskModel
{
    protected $dataRoot = '';
    protected $logFilename = '';

    public function __construct()
    {
        $this->dataRoot = dirname(__DIR__) . '/data/';
        $this->logFilename = $this->dataRoot . '/log/task-' . date('Ym') . '.log';
        if (!file_exists(dirname($this->logFilename))) {
            mkdir(dirname($this->logFilename), 0777, true);
        }
    }

    public function run($isEcho = true)
    {
        $weekday = date('w');
        // $weekday = 2;
        $weekdayName = ['天', '一', '二', '三', '四', '五', '六'][$weekday];
        if ($weekday == 5) {
            savelog($this->logFilename, '星期' . $weekdayName . ' 不执行', $isEcho);
            return;
        }

        $spiderModel = new SpiderModel();
        $isDlt = $weekday == 1 || $weekday == 3 || $weekday == 6;
        $isSsq = $weekday == 2 || $weekday == 4 || $weekday == 0;
        if ($isDlt) {
            $message = $spiderModel->fetchDlt($isEcho);
        }
        if ($isSsq) {
            $message = $spiderModel->fetchSsq($isEcho);
        }
        if ($message['code'] !== 200) {
            savelog($this->logFilename, '采集数据失败：' . $message['message'], $isEcho);
            return;
        }
        savelog($this->logFilename, '采集数据成功：' . $message['message'], $isEcho);
    }
}
